<template>
  <div>
    <div class="header-pc" v-if="$store.state.isHeadshow">
      <div
        class="container"
        style="background: #fff; height: 100px; width: 100%; max-width: 1200px"
      >
        <div class="header-top">
          <div class="logo-wrap">
            <img
              src="../assets/images/logo.png"
              style="width: 192px; height: 100%"
              alt=""
            />
          </div>
          <div class="input-box" style="position: relative">
            <el-input
              placeholder="请输入内容"
              @input="handleInputChange"
              v-model.trim="inputValue"
              class="input"
            >
              <i slot="suffix" class="el-input__icon el-icon-search"></i>
            </el-input>
            <div class="search-clc" @click="hanldeGetInputValue"></div>
          </div>
        </div>
      </div>
      <div
        class="container nav"
        :style="`background:${$store.state.backcolor}`"
      >
        <div
          :style="`height: 50px;
            width: 100%;
            filter: ${$store.state.filter};
            user-select: none;
            position: absolute;
            background: ${$store.state.backcolor};
            opacity:${$store.state.opacity};
            z-index: 2;`"
        ></div>
        <div class="header-bottom" :style="`color:${$store.state.color};`">
          <div class="menu-list">
            <div
              :style="{
                '--hover-color': $store.state.hocolor
                  ? $store.state.hocolor
                  : hoverColor,
              }"
              @click="handleRouter(item)"
              class="menu"
              :class="index == $store.state.activeIndex ? 'active' : ''"
              v-for="(item, index) in menuList"
              :key="index"
            >
              <div>{{ item.name }}</div>
            </div>
          </div>
          <div class="login-region" v-if="!$store.state.userData.id">
            <el-button
              @click="handleRouter({ url: '/login' })"
              :style="`color:${
                $store.state.color == '#737980' ? '#fff' : '#fff'
              };background:${hoverColor}`"
              >登录</el-button
            >
          </div>
          <div class="login-region" v-else>
            <el-popover
              popper-class="pop-user-info"
              placement="bottom"
              width="100"
              trigger="hover"
            >
              <ul>
                <li @click="handleGoUrl">
                  <i class="fa fa-power-off"></i>个人中心
                </li>
                <li @click="handleOpenDialog">
                  <i class="fa fa-power-off"></i>修改密码
                </li>
                <li @click="handleIsBackLogin" v-if="$store.state.islogin">
                  <i class="fa fa-edit"></i>退出登录
                </li>
              </ul>
              <div
                slot="reference"
                style="font-weight: bold; font-size: 16px; cursor: pointer"
              >
                {{
                  $store.state.userData.type == "0"
                    ? username
                    : $store.state.userData.userName
                }}
              </div>
            </el-popover>
          </div>
        </div>
      </div>
    </div>
    <!-- 修改密码弹窗 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px">
      <el-form
        :model="ruleForm"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
        :rules="passRules"
      >
        <el-form-item class="code-item">
          <div class="title"><span class="red">*</span>旧密码:</div>
          <el-input
            type="password"
            v-model.trim="ruleForm.oldPassword"
            show-password
            class="input"
            placeholder="请输入旧密码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="pass" class="code-item">
          <div class="title"><span class="red">*</span>新密码:</div>
          <el-input
            type="password"
            v-model.trim="ruleForm.newPassword"
            show-password
            class="input"
            placeholder="请输入至少8位的新密码"
            clearable
          ></el-input>
        </el-form-item>
        <el-form-item prop="confirmPassword" class="code-item">
          <div class="title"><span class="red">*</span>确认新密码:</div>
          <el-input
            type="password"
            v-model.trim="ruleForm.isPassword"
            show-password
            class="input"
            placeholder="确认新密码"
            clearable
          ></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleEditPassword">确 定</el-button>
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import { Base64 } from "js-base64";
import { validConfirmPass, checkPhone, checkPass } from "@/utils/fromcheck.js";
import { headLineTitle, updateInfo, homeSearch } from "@/api/homePage.js";
import { STATUS_CODE_OK } from "@/config";
import { mapActions } from "vuex";
import store from "@/store";
export default {
  // 头部菜单组件
  name: "MHeader1",
  props: {
    // 不同的数值匹配不同的页面
    // 0：首页；1：智能娃娃管理平台；2：课程资源...以此类推
    activeIndex: {
      type: [Number, String],
      default: 10,
    },
    // 背景颜色
    backcolor: {
      type: String,
      default: "#1968FA",
    },
    // 字体颜色
    color: {
      type: String,
      default: "#fff",
    },
    // 透明度
    opacity: {
      type: String,
      default: "1",
    },
    // 选中颜色
    hocolor: {
      type: String,
      default: "#fff",
    },
    // 摩斯遮挡
    filter: {
      type: String,
      default: "blur(0px)",
    },
    // 是否退出登录
    islogin: {
      type: Boolean,
      default: true,
    },
  },
  computed: {
    inputValue: {
      get() {
        return this.$store.state.searchValue; // 从 Vuex 中读取 searchValue
      },
      set() {
        // 当尝试设置时，实际上我们不直接修改，而是触发 action 更新 Vuex
      },
    },
    // 计算属性自动计算countDownTime,并转换为倒计时
    username() {
      let mystr =
        this.$store.state.userData.userName.substring(0, 4 - 1) +
        "****" +
        this.$store.state.userData.userName.substring(7 + 1);
      return mystr;
    },
  },
  data() {
    return {
      validConfirmPass,
      checkPhone,
      checkPass,
      passRules: {
        pass: [
          {
            validator: (rules, value, callback) =>
              this.checkPass(this.ruleForm.newPassword, callback),
            trigger: "blur",
          },
        ],

        confirmPassword: [
          {
            validator: (rules, value, callback) =>
              this.validConfirmPass(
                this.ruleForm.newPassword,
                this.ruleForm.isPassword,
                callback
              ),
            trigger: "blur",
          },
        ],
      },
      ruleForm: {
        oldPassword: "",
        newPassword: "",
        isPassword: "",
      },
      dialogTitle: "修改密码",
      dialogVisible: false,
      userdata: {},
      hoverColor: "#1968FA",
      // inputValue: "",
      mobileMenuShow: false,
      menuList: [
        {
          name: "首页",
          url: "/",
          type: "",
        },
        {
          name: "智能娃娃管理平台",
          url: "http://isc.jz1x.com/#/login",
          type: "w",
        },
        // {
        //   name: "课程资源",
        //   url: "/courseresources",
        //   type: "",
        // },
        {
          name: "赛项资源",
          url: "/eventresources",
          type: "",
        },
        {
          name: "1+X证书",
          url: "/bookresources",
          type: "",
        },
        {
          name: "技能培训",
          url: "/skillsresources",
          type: "",
        },
        {
          name: "金职大讲堂",
          url: "/courseresources",
          type: "",
        },
        {
          name: "行业资源",
          url: "/industryresources",
          type: "",
          // /industryresources
        },
      ],
      dataList: [],
    };
  },
  created() {
    if (localStorage.getItem("USER_DATA")) {
      this.userdata = JSON.parse(localStorage.getItem("USER_DATA"));
    }
    // this.handleHeadLineTitle();
  },
  methods: {
    ...mapActions(["setToken", "loginOut"]),
    // 搜索框value值控制
    handleInputChange(e) {
      this.$store.dispatch("setSearchValue", e);
    },
    // 打开弹窗个
    handleOpenDialog() {
      this.dialogVisible = true;
    },
    // 修改密码
    async handleEditPassword() {
      if (this.ruleForm.oldPassword == "") {
        this.$notify.warning({
          title: "提示",
          message: "请输入旧密码",
        });
        return;
      }
      if (this.ruleForm.newPassword == "") {
        this.$notify.warning({
          title: "提示",
          message: "请输入新密码",
        });
        return;
      }
      if (this.ruleForm.isPassword != this.ruleForm.newPassword) {
        this.$notify.warning({
          title: "提示",
          message: "请确保两次输入的密码保持一致",
        });
        return;
      }
      if (this.ruleForm.newPassword.length < 8) {
        this.$notify.warning({
          title: "提示",
          message: "请输入8位新密码",
        });
        return;
      }
      let { data } = await updateInfo({
        oldPassword: Base64.encode(this.ruleForm.oldPassword),
        newPassword: Base64.encode(this.ruleForm.isPassword),
        type: this.$store.state.userData.type,
      });
      if (data.code == STATUS_CODE_OK) {
        if (data.data) {
          this.setToken(data.data.token);
          this.$message({
            message: "修改密码成功!",
            type: "success",
          });
          if (this.$route.fullPath != "/") {
            this.$router.push("/");
          } else {
            window.location.reload();
          }
          this.dialogVisible = false;
        } else {
          this.$notify.warning({
            title: "提示",
            message: data.msg,
          });
          return;
        }
      }
    },
    async handleHeadLineTitle() {
      let { data } = await headLineTitle();
      this.dataList = data.data;
      this.dataList.forEach((item, index) => {
        this.menuList.forEach((eitem) => {
          if (item == eitem.name) {
            this.dataList[index] = eitem;
          }
          if (item != eitem.name) {
            this.dataList[index] = { name: item, url: "/" };
          }
        });
      });
    },
    async handleIsBackLogin() {
      try {
        await this.$confirm(`确定退出登录?`, "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        });
        this.handleLoginOut();
      } catch {
        console.log("取消");
      }
    },
    handleLoginOut() {
      this.loginOut();
      if (this.$route.fullPath == "/") {
        setTimeout(() => {
          window.location.reload();
        }, 100);
      } else {
        this.$router.push("/");
      }
    },
    handleGoUrl() {
      if (this.$route.fullPath == "/information") {
        return;
      } else {
        if (store.state.userData.type == "1") {
          this.$router.push("/information");
        } else {
          this.$router.push("/information");
        }
      }
    },
    async handleHomeSearch() {
      let { data } = await homeSearch({
        searchValue: this.inputValue ? this.inputValue : "",
        pageNum: 1,
        pageSize: 20,
      });
      if (data.code == STATUS_CODE_OK) {
        this.$store.dispatch("setSearchData", data.data.records);
        this.$store.dispatch("setSearchTotal", data.data.total);
      }
    },
    hanldeGetInputValue() {
      // this.$emit("hanldeGetValue", this.inputValue);
      if ("/search" === this.$router.currentRoute.fullPath) {
        sessionStorage.setItem("searchvalue", this.inputValue);
        this.handleHomeSearch();
        return;
      } else {
        sessionStorage.setItem("searchvalue", this.inputValue);
        this.$router.push({
          path: "/search",
        });
        this.handleHomeSearch();
      }
    },
    // 路由跳转
    handleRouter(item) {
      if (item.type != "w") {
        if (item.url == "/" && item.name != "首页") {
          this.$message("功能暂未开放！敬请期待~");
          return;
        }
        if (item.url === this.$router.currentRoute.fullPath) {
          return;
        }
        sessionStorage.setItem("resourcesTab", "1");
        this.$router.push(item.url);
      } else {
        window.open(item.url, "_blank");
        // window.location.href = item.url;
      }
    },
  },
};
</script>

<style scoped lang="scss">
$green: #fff;
::v-deep .el-form-item__content {
  display: flex;
  margin-left: 0px !important;
}
::v-deep .el-form-item__error {
  margin-left: 110px;
}
.code-item {
  width: 400px;
  .title {
    text-align: right;
    width: 150px;
    padding: 0px 10px;
    .red {
      color: red;
    }
  }
}
.pop {
  display: flex;
  flex-direction: column;
  align-items: center;
}
.po:hover {
  color: rgb(25, 104, 250);
}
.input-box {
  display: flex;
  align-items: center;
  // margin-bottom: 30px;
  // width: 400px;
}
.dia-til {
  width: 120px;
  text-align: right;
  margin-right: 10px;
  padding: 0px 10px;
  .red {
    color: red;
    margin-right: 5px;
  }
}
.header-pc {
  .nav {
    z-index: 2;
    position: absolute;
    width: 100%;
    display: flex;
    justify-content: space-evenly;
  }
  background-color: $green;
  .container {
    .header-top {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
    .logo-wrap {
      display: flex;
      align-items: center;
      padding-top: 20px;
      cursor: pointer;
      .logo {
        height: 52px;
        margin-right: 12px;
        width: 52px;
        background: pink;
      }
      .logo-text {
        height: 52px;
        line-height: 52px;
        font-size: 18px;
      }
    }
    .header-bottom {
      display: flex;
      align-items: center;
      justify-content: space-between;
      // width: 1200px;
      width: 100%;
      max-width: 1200px;
      position: absolute;
      height: 50px;
      z-index: 2;
      .login-region {
        width: 100px;
        display: flex;
        align-items: center;
        justify-content: space-evenly;
      }
      .menu-list {
        display: flex;
        align-items: center;
        font-size: 16px;
        margin-left: 12px;
        .menu:hover {
          color: var(--hover-color);
          // padding: 10px 0px;
          font-weight: bold;
        }
        .menu {
          padding: 0 16px;
          cursor: pointer;
          &:first-child {
            padding-left: 0;
          }
          &:last-child {
            padding-right: 0;
          }

          &.active {
            color: var(--hover-color);
            border-bottom: 5px solid var(--hover-color);
            padding: 11px 0px;
            font-weight: bold;
          }
        }
      }
    }
  }
}
.header-mobile {
  background-color: $green;
  display: flex;
  align-items: center;
  justify-content: space-between;
  position: relative;
  height: 60px;
  .logo-wrap {
    display: flex;
    align-items: center;
    cursor: pointer;
    .logo {
      display: block;
      height: 35px;
      margin-right: 12px;
    }
    .logo-text {
      display: block;
      height: 35px;
    }
  }
  .menu-wrap {
    cursor: pointer;
    display: flex;
    align-items: center;
    .icon {
      color: #fff;
      font-size: 30px;
    }
  }

  .menu-list {
    position: absolute;
    top: 60px;
    left: 0;
    right: 0;
    z-index: 101;
    background-color: $green;
    font-size: 16px;
    .menu {
      padding: 10px 15px;
      cursor: pointer;
      color: #fff;
      &:hover,
      &.active {
        color: var(--hover-color);
      }
    }
  }
}
.input-box {
  margin-top: 20px;
  display: flex;
  .search-clc {
    // background: pink;
    width: 30px;
    height: 38px;
    right: 0px;
    position: absolute;
    z-index: 2;
    cursor: pointer;
  }
  .input {
    width: 308px;
    height: 44px;
  }
}
</style>
